/// <reference path="../../../typings/index.d.ts" />

const WXAPP = getApp();
const util = require('../../utils/util.js')
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //用户个人信息
    avatarUrl: "",
    nickName: "",
    openID: "",
    isLogin: false,
    //决定用户点击的是轮播图的哪一侧
    leftBind:true,
    rightBind:false,
    orderLocation:null,//预定的浴室
    orderWaitTime:null,//预计的等待时间
    orderTime:0,
    orderHistoryCount:0,//个人历史订单的数量
    orderShow:false,
    orderList:[
      
    ],
    credit:null,//用户信用分
    notZero:true,
    skiporder:0
  },
  

  leftTab(e) {
    this.setData({
      leftBind:true,
      rightBind:false,
    })
  },

  rightTab(e) {
    this.setData({
      leftBind: false,
      rightBind: true,
    })
    console.log(this.data.orderHistoryCount);

    console.log('准备更改历史订单信息   '+WXAPP.globalData.openid)
    var that = this;

  },

  
  add_address_fun: function () {
    wx.navigateTo({
      url: 'add_address/add_address',
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    this.getGlobalData();
    wx.authorize({
      scope: "scope.userInfo",
      success: () => {
        console.log("已授权");
      },
      fail: (err) => {
        console.error("拒绝授权", err);
      }
    });

    var that = this;
    wx.cloud.callFunction({
      name: 'orderCount',
      data: {
        openid: WXAPP.globalData.openid
      }
    }).then(tmp => {
      wx.cloud.callFunction({
        name: 'sortOrderHistory',
        data: {
          openid: WXAPP.globalData.openid
        }
      }).then(res => {
        console.log('onshow     ' + tmp.result.total)
        if (tmp.result.total != 0) {//setdata会有加载的延迟
          var tmpDate = new Date(res.result.data[0].datetime)
          that.setData({
            orderLocation: res.result.data[0].domitory,
            orderWaitTime: util.formatTime(tmpDate)
          })//onload的时候就把当前预定的订单信息加载给前端

          db.collection("orderStatus")
            .doc(WXAPP.globalData.openid)
            .get()
            .then(las=>{
              console.log('fix test  '+las.data.predit)
              that.setData({
                orderWaitTime: las.data.predit+"  分钟 "
              })
            })

        }
      })
    });
    

    

    // db.collection('orderHistory')
    //   .where({
    //     _openid: "oU2Tk5E3dCPIDcVEe8pv_eaOnhyA"
    //   })
    //   .orderBy('datetime', 'desc')
    //   .skip(0)
    //   .limit(4)
    //   .get()
    //   .then(sor=>{
    //     console.log(sor);
    //     console.log('test  '+sor.data[0].domitory)
    //   })

    // console.log('skip  '+this.data.skiporder)
    // this.data.skiporder+=4;
 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */

  onShow(){
    db.collection('orderStatus')
      .where({
        _id: WXAPP.globalData.openid
      })
      .get()
      .then(res => {
        this.setData({
          orderShow: res.data[0].orderNow,
        })
      })

    wx.cloud.callFunction({
      name: 'orderCount',
      data: {
        openid: WXAPP.globalData.openid
      }
    }).then(res => {
      this.setData({
        orderHistoryCount: res.result.total
      })
      if (res.result.total!=0){
        this.setData({
          notZero:true
        })
      }
      if (res.result.total != 0) {//订单总数不为0的时候才可以写入历史订单
        this.data.skiporder = Math.min(4, that.data.orderHistoryCount);
        wx.cloud.callFunction({
          name: 'sortOrderHistory',
          data: {
            openid: WXAPP.globalData.openid
          }
        }).then(ad => {
          console.log('能进入回调吗    ' + that.data.orderHistoryCount)
          //console.log(res.result.data[0].domitory);
          for (var i = 0; i < Math.min(4, that.data.orderHistoryCount); ++i) {//不通过云函数最多能读100个
            //初始最多可以增加4个历史记录，加速页面渲染
            var ol = that.data.orderList;
            var obj = {};
            var tmpDate = new Date(ad.result.data[i].datetime)
            obj.location = ad.result.data[i].domitory;
            obj.time = util.formatTime(tmpDate);
            ol.push(obj);//添加到历史订单的数组中用来展示
            that.setData({ orderList: ol });
            //console.log(i);
          }
          //console.log('日期测试' + util.formatTime(tmpDate));
          console.log(that.data.orderList);
        })
      }
    });

    

    var that = this;

    
    

    db.collection('userInfo')//每次切换到该页面都进行信用分的更新，因为要展示给用户
      .where({
        _openid: WXAPP.globalData.openid
      })
      .get()
      .then(cre => {
        that.setData({
          credit: cre.data[0].credit
        })
      })
    
  },

  onReady: function () {
    
  },

  /**
   * 将app.globalData注入到本页面的data中，来给wxml使用
   */
  getGlobalData: function () {
    if (WXAPP.globalData.isLogin) {
      this.setData({
        avatarUrl: WXAPP.globalData.userInfo.avatarUrl,
        nickName: WXAPP.globalData.userInfo.nickName,
        openID: WXAPP.globalData.openid,
        isLogin: WXAPP.globalData.isLogin
      });
    }
  },

  onTapLogin: function (res) {
    console.log("tap login");
    console.log(res);
    this.getOpenid();
  },


  getOpenid: function () {
    let that = this;
    wx.cloud.callFunction({
      name: 'getOpenID',
    }).then((res) => {
      WXAPP.globalData.isLogin = true;
      this.data.openid = res.result.openid;
      console.log("OpenID: ", this.data.openid);
      wx.getUserInfo({
        success(res) {
          console.log(res);
          WXAPP.globalData.userInfo = res.userInfo;
          that.getGlobalData();
          console.log('欢迎！', res.userInfo.nickName);
          console.log(WXAPP.globalData.userInfo);
        },
        fail(err) {
          console.error("获取用户信息失败", err)
        }
      });
    });
  },
  

  OnclickOrder:function(){
    wx.redirectTo({
      url: '../home/home',
    })
  },

  orderCancal:function(){
    var that = this;
    wx.showModal({
      title: '取消预约',
      content: '确认取消当前预约？\r\n(取消预约会降低信用分)',
      success(res) {
        if (res.confirm) {
          console.log('2现在是否可以展示   ' + that.data.orderShow);
          wx.cloud.callFunction({//更新按钮和订单状态
            name: 'updateStatus',
            data: {
              _id:WXAPP.globalData.openid,
              canPressOrder: true,
              isHideOrderButton: false,
              isOrdered: false,
              orderNow: false
            }
          }).then(a=>{//这个回调用来在当前界面获取订单状态
            db.collection('orderStatus')
              .where({
                _id: "test"
              })
              .get()
              .then(tmp => {
                that.setData({
                  orderShow: tmp.data[0].orderNow,
                })
                console.log('检测数据库2   ' + tmp.data[0].orderNow);
              })
          })

          wx.cloud.callFunction({
            name: 'sortOrderHistory',
            data: {
              openid: WXAPP.globalData.openid
            }
          }).then(ord => {
            console.log('能不能开始删除呢')
            wx.cloud.callFunction({
              name: 'orderRemove',
              data: {
                _id: ord.result.data[0]._id
              }
            })
          })

          console.log('2现在是否可以展示   '+that.data.orderShow);          
          db.collection('userInfo')
            .where({
              _openid: WXAPP.globalData.openid
            })
            .get()
            .then(cre => {
              wx.cloud.callFunction({
                name: 'updateCredit',
                data: {
                  _id: WXAPP.globalData.openid,
                  credit: Math.max(cre.data[0].credit - 1,0)
                }
              })
            })
            
          db.collection('userInfo')
            .where({
              _openid: WXAPP.globalData.openid
            })
            .get()
            .then(cre => {
              that.setData({
                credit:Math.max(cre.data[0].credit-1,0)
              })
            }) 

          if(that.data.orderHistoryCount==1){
            that.setData({
              orderHistoryCount:0,
              notZero:false,
            })
          }

          wx.cloud.callFunction({
            name: "removeFromQueue"
          }).then(res => {
            console.log("success remove from queue\n", res);

          }).catch(err => {
            console.error("fail remove from queue\n", err);
          })
        } else if (res.cancel) {
          console.log('用户未取消预约')
        }
      }
    })
  },

  loadMore(){
    var that = this;
    wx.cloud.callFunction({
      name: 'orderCount',
      data: {
        openid: WXAPP.globalData.openid
      }
    }).then(res=>{
      if (res.result.total != 0 && that.data.orderList.length<res.result.total) {
        var gap = that.data.orderHistoryCount - that.data.orderList.length;
        wx.cloud.callFunction({
          name: 'showOrderHistory',
          data: {
            openid: WXAPP.globalData.openid,
            sk: Math.min(4, res.result.total),
            lim:Math.min(4,gap)
          }
        }).then(ad => {
          console.log('数组    ' + that.data.orderList.length)
          console.log('订单    ' + that.data.orderHistoryCount) 
          console.log('差值    ' + gap)
          if (that.data.orderList.length < that.data.orderHistoryCount){//历史订单展示的数量不能超过总数
          console.log('skip   '+this.data.skiporder)
            for (var i = 0; i < Math.min(4, gap); ++i) {//一次最多读2个，最少是补齐二者差值
            //初始可以增加4个历史记录，加速页面渲染
            var ol = that.data.orderList;
            var obj = {};
            obj.location = ad.result.data[i].domitory;
            obj.time = ad.result.data[i].datetime;
            ol.push(obj);//添加到历史订单的数组中用来展示
            that.setData({ orderList: ol });
            //console.log(i);
          }
            console.log(that.data.orderList);
          }else{
            console.log("订单够啦")
          }
        })
      }else{
        wx.showToast({
          title: '已经是全部订单啦',
          icon: 'none',
          duration: 2000
        });
      }
    })
  }

})
